package com.hckjsec.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hckjsec.common.constant.Constants;
import com.hckjsec.common.core.domain.entity.SysRole;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class ComUtil {
    public static Map<String,String[]> cityHt=new Hashtable<String, String[]>();//地图对应参数
    public static Map<String,String[]> cityCountyHt=new Hashtable<String, String[]>();//衡水市
    static {
        cityHt.put("102", //衡水市
                new String[] {"hengshui","衡水市","hbhs","安平县,饶阳县,深州市,武强县,冀州区,桃城区,武邑县,阜城县,景县,枣强县,故城县"});
        cityCountyHt.put("安平县",new String[]{"117"});
        cityCountyHt.put("饶阳县",new String[]{"114","117"});
        cityCountyHt.put("深州市",new String[]{"115"});
        cityCountyHt.put("武强县",new String[]{"123"});
        cityCountyHt.put("冀州区",new String[]{"120"});
        cityCountyHt.put("桃城区",new String[]{"119"});
        cityCountyHt.put("武邑县",new String[]{"121"});
        cityCountyHt.put("阜城县",new String[]{"122"});
        cityCountyHt.put("景县",new String[]{"116"});
        cityCountyHt.put("枣强县",new String[]{"118"});
        cityCountyHt.put("故城县",new String[]{"113"});
    }


    public static ConcurrentHashMap<String, String> getTokenByAppidMap =  new ConcurrentHashMap<String, String>();//缓存微信AccessToken
    public static String WX_API_BASE = "https://api.weixin.qq.com";// 微信请求地址
    public static String WX_GETUSER = "/sns/jscode2session";// 换取openid
    public static String WX_GETUSER_GZH = "/sns/oauth2/access_token";// 换取openid-公众号
    public static String WX_GETUNIONID_GZH = "/cgi-bin/user/info";// 换取unionid-公众号
    public static String WX_GETUNIONID2_GZH = "/sns/userinfo";// 换取unionid-公众号2

    public static String WX_ACCESSTOKEN = "/cgi-bin/token";// 获取AccessToken
    public static String WX_MESSAGE = "/cgi-bin/message/subscribe/send";// 小程序订阅消息
    public static String WX_CODEUNLIMIT = "/wxa/getwxacodeunlimit";// 小程序码
    //冀时办
    public static String JISHIBAN_URL="http://zwfwtest.ccbft.com:8039/auth/getAccessLinkForUserTmpMsg";
    public static String JISHIBAN_APPID="WGZ_APP_HB_001";
    public static String JISHIBAN_PWD="W257ZC2R94";

    public static String CONFIG_CATEGORY = "applets_category";// 类别字典
    public static String CONFIG_PURPOSE = "applets_purpose";// 用途字典
    public static String CONFIG_PLACE = "applets_place";// 使用地字典
    public static String CONFIG_IANGUAGES = "applets_ianguages";// 语种字典
    public static String CONFIG_MATERIAL = "applets_material";// 材料字典
    public static String CONFIG_MATTER_TYPE = "sys_matter_type";// 事项分类
    public static String CONFIG_CHARGE = "applets_charge";// 费用字典
    public static String CONFIG_PERSONNELTYPE = "applets_personneltype";// 证件人员类型字典
    public static String CONFIG_COMPANYTYPE = "applets_companytype";// 证件单位类型字典
    public static String CONFIG_MATTER_TEXT_MATCH = "5005,5006,5011,5021,5064,5112";// 文本相符使用地 美国,俄罗斯,韩国,白俄罗斯,奥地利,哈萨克斯坦
    public static String CONFIG_TEXT_MATCH_MATTER_NUMBER = "013501";// 文本相符事项编号
    public static String CONFIG_MATTER_NOTARIZATION_FEE = "3001";//公证费编号
    public static String CONFIG_NATURE = "law_nature";// 单位性质
    public static String CONFIG_LAW_MATTER_TYPE = "law_matter_type";// 政务服务事项类型
    public static String CONFIG_LAW_EXECUTE_TYPE = "law_execute_type";// 政务服务办件类型
    //公共法律服务
    public static String LAW_SECRETID = "AKIDyhDbqGoU8YKrCIkzZN3UhjIp59DAna4M";//短信secretId
    public static String LAW_SECRETKEY = "3pNeleIjuuhQuJSXPL4Xsy3uV5RYw522";//短信secretKey
    public static String LAW_SMSSDKAPPID = "1400511724";//短信SmsSdkAppid
    public static String LAW_SIGN = "容城县司法局";//短信sign
    public static String LAW_ZW_PHONE_USER = "13833238646,15103326383,13785250128";//政务服务通知人员
    public static String LAW_ZW_ID_USER = "156";//政务服务通知人员id

    public static String CONFIG_LEAVE = "oa_leave_type";// 请假类型
    public static String CONFIG_EXPENCE = "oa_expense_type";// 报销类型

    /**
     * 根据listmap添加到map
     */
    public static Map<String, String> mapListByMap(List<Map<String, String>> list, String key) {
        Map<String,String> res = new HashMap<>();
        for (Map<String, String> stringStringMap : list) {
            String uid = null;
            String areaName = null;
            for (Map.Entry<String,String> entry:stringStringMap.entrySet()){
                if (key.equals(entry.getKey())){
                    uid = entry.getValue();
                }else {
                    areaName = entry.getValue();
                }
            }
            res.put(uid,areaName);
        }
        return res;
    }


    /**
     * 根据listmap添加到map value为BigDecimal
     */
    public static Map<String, String> mapListByBigDecimalMap(List<Map<String, BigDecimal>> list, String key) {
        Map<String,String> res = new HashMap<>();
        for (Map<String, BigDecimal> stringStringMap : list) {
            String uid = null;
            String areaName = null;
            for (Map.Entry<String,BigDecimal> entry:stringStringMap.entrySet()){
                if (key.equals(entry.getKey())){
                    uid = String.valueOf(entry.getValue());
                }else {
                    areaName = String.valueOf(entry.getValue());
                }
            }
            res.put(uid,areaName);
        }
        return res;
    }

    /**
     * 根据listmap添加到map value为Integer
     */
    public static Map<String, String> mapListByBigIntegerMap(List<Map<String, Integer>> list, String key) {
        Map<String,String> res = new HashMap<>();
        for (Map<String, Integer> stringStringMap : list) {
            String uid = null;
            String areaName = null;
            for (Map.Entry<String,Integer> entry:stringStringMap.entrySet()){
                if (key.equals(entry.getKey())){
                    uid = String.valueOf(entry.getValue());
                }else {
                    areaName = String.valueOf(entry.getValue());
                }
            }
            res.put(uid,areaName);
        }
        return res;
    }
    /**
     * 遍历实体类并进行赋值
     */
    public static void setFields(Object object,String paramdetailnumber,String content){
        Field[] fields = object.getClass().getDeclaredFields();
        for(int i=0; i<fields.length; i++) {
            Field f = fields[i];
            f.setAccessible(true);
            String attributeName = f.getName();
            String methodName = attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1);
            try {
                if (attributeName.equals(paramdetailnumber)) {
                    Method setMethod = object.getClass().getMethod("set" + methodName, String.class);
                    setMethod.invoke(object, content);
                }
               //System.out.println("属性名:" + f.getName() + " 属性值:" + f.get(object));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param entity 对象
     * @param fieldName 对象中某属性名称
     * @return
     */
    public static boolean checkFields(Object entity,String fieldName){
        boolean flag=true;
        try {
            Field field=entity.getClass().getDeclaredField(fieldName);
        }catch (Exception e){
            flag=false;
        }
        return flag;
    }

    /**
     * 单个对象的某个键的值
     *
     * @param object
     *            对象
     *
     * @param key
     *            键
     *
     * @return Object 键在对象中所对应得值 没有查到时返回空字符串
     */
    public static String getValueByKey(Object object, String key) {
        String msg ="";
        Field[] fields = object.getClass().getDeclaredFields();
        for(int i=0; i<fields.length; i++) {
            Field f = fields[i];
            f.setAccessible(true);
            String attributeName = f.getName();
            String methodName = attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1);
            try {
                System.out.println("属性名:" + f.getName() + " 属性值:" + f.get(object));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return msg;
    }



    /**
     * 设置cache key（微信oppenid）
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    public static String getWechatCacheKey(String configKey)
    {
        return Constants.WECHAT_USER_OPENID + configKey;
    }

    /**
     * 设置节假日
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    public static String getHolidayCacheKey(String configKey)
    {
        return Constants.SYS_HOLIDAY_KEY + configKey;
    }

    /**
     * 设置cache key（公司OA）
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    public static String getOaCacheKey(String configKey)
    {
        return Constants.APP_USER_TOKEN + configKey;
    }

    /**
     * 设置cache key（微信oppenid）
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    public static String getVerificationKey(String configKey)
    {
        return Constants.WECHAT_VERIFICATION_USER + configKey;
    }

    /**
     * 设置cache key（微信oppenid）
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    public static String getWechatBusinessKey(String configKey)
    {
        return Constants.WECHAT_BUSINESSID + configKey;
    }


    /**
     * 设置cache key（微信oppenid）
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    public static String getWechatVideoRoomCacheKey(String configKey)
    {
        return Constants.WECHAT_VIDEO_USER_ROOM + configKey;
    }

    /**
     * 设置cache key（网站登录）
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    public static String getWebSiteCodeCacheKey(String configKey)
    {
        return Constants.WEB_SITE_MESSAGE_CODE + configKey;
    }

    /**
     * 通过身份证号码获取出生日期、性别、年龄
     * @param certificateNo
     * @return 返回的出生日期格式：1990-01-01 性别格式：F-女，M-男
     */
    public static Map<String, String> getBirAgeSex(String certificateNo) {
        String birthday = "";
        String age = "";
        String sexCode = "";

        int year = Calendar.getInstance().get(Calendar.YEAR);
        char[] number = certificateNo.toCharArray();
        boolean flag = true;
        if (number.length == 15) {
            for (int x = 0; x < number.length; x++) {
                if (!flag)
                    return new HashMap<String, String>();
                flag = Character.isDigit(number[x]);
            }
        } else if (number.length == 18) {
            for (int x = 0; x < number.length - 1; x++) {
                if (!flag)
                    return new HashMap<String, String>();
                flag = Character.isDigit(number[x]);
            }
        }
        if (flag && certificateNo.length() == 15) {
            birthday = "19" + certificateNo.substring(6, 8) + "-" + certificateNo.substring(8, 10) + "-"
                    + certificateNo.substring(10, 12);
            sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 3, certificateNo.length()))
                    % 2 == 0 ? "F" : "M";
            age = (year - Integer.parseInt("19" + certificateNo.substring(6, 8))) + "";
        } else if (flag && certificateNo.length() == 18) {
            birthday = certificateNo.substring(6, 10) + "-" + certificateNo.substring(10, 12) + "-"
                    + certificateNo.substring(12, 14);
            sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 4, certificateNo.length() - 1))
                    % 2 == 0 ? "F" : "M";
            age = (year - Integer.parseInt(certificateNo.substring(6, 10))) + "";
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("birthday", birthday);
        map.put("age", age);
        map.put("sexCode", sexCode);
        return map;
    }

    /**
     * 判断是否是文本相符国家
     */
    public static Boolean isTextMatch(String place){
        Boolean flag=false;
        String[] fields=CONFIG_MATTER_TEXT_MATCH.split(",");
        for(int i=0; i<fields.length; i++) {
            if (place.equals(fields[i])){
                flag=true;
            }
        }
        return flag;
    }

    /**
     * 返回一个i位数的随机数
     * @param i
     * @return
     */
    public static String getRandom(int i) {
        Random jjj = new Random();
        if (i == 0)
            return "";
        String jj = "";
        for (int k = 0; k < i; k++) {
            jj = jj + jjj.nextInt(9);
        }
        return jj;
    }

    /**
     * 百分比
     * @param detailTotalNumber  数
     * @param totalNumber  总数
     *                    占比=数/总数
     * @return
     */
    public static String percentInstance(Integer detailTotalNumber, Integer totalNumber) {
        if(detailTotalNumber <= 0 || totalNumber<=0){
            return "0.00";
        }
        Double bfTotalNumber = Double.valueOf(detailTotalNumber);
        Double zcTotalNumber = Double.valueOf(totalNumber);
        double percent = bfTotalNumber/zcTotalNumber;
        //获取格式化对象
        NumberFormat nt = NumberFormat.getPercentInstance();
        //设置百分数精确度2即保留两位小数
        nt.setMinimumFractionDigits(2);
        return nt.format(percent).replace("%","");
    }

    /**
     * 判断文件是否是视频
     * @param i
     * @return
     */
    public static String getIsVideo(String fileName) {
        String flag = "false";
        String [] typeArr = new String[]{"mp4","flv","avi","rm","rmvb","wmv"};
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        for (int i = 0; i < typeArr.length; i++) {
            if (suffix.equals(typeArr[i])){
                flag = "true";
            }
        }
        return flag;
    }

    /**
     * 判断角色最高级别
     * @param i
     * @return
     */
    public static Integer getHighestRole(List<SysRole> roles) {
        Map<String,Integer> roleHt = new HashMap<String,Integer>();
        roleHt.put("admin",9);
        roleHt.put("lawadmin",8);
        roleHt.put("ompanyadmin",7);
        roleHt.put("ordinaryuser",6);
        roleHt.put("propaganda",5);
        int max = 5;
        for (SysRole sysRole : roles)
        {
            String roleKey = sysRole.getRoleKey();
            if (roleHt.containsKey(roleKey)){
                int roleNumber = roleHt.get(roleKey);
                if (roleNumber > max){
                    max = roleNumber;
                }
            }
        }
        return max;
    }

    /**
     * 判断list<String> 是否都是以指定字符串开头
     * @param i
     * @return
     */
    public static Boolean isLastStr(List<String> list,String str){
        boolean flag = true;
        for (String msg : list){
            if (!msg.startsWith(str)){
                flag = false;
                break;
            }
        }
        return flag;
    }


    /**
     * 判断你一个类是否存在某个属性（字段）
     *
     * @param field 字段
     * @param obj   类对象
     * @return true:存在，false:不存在, null:参数不合法
     */
    public static Boolean isExistField(String field, Object obj) {
        if (obj == null || StringUtils.isEmpty(field)) {
            return null;
        }
        Object o = JSON.toJSON(obj);
        JSONObject jsonObj = new JSONObject();
        if (o instanceof JSONObject) {
            jsonObj = (JSONObject) o;
        }
        return jsonObj.containsKey(field);
    }


    /**
         * 根据属性名获取属性值
          * */
     public static Object getFieldValueByName(String fieldName, Object o) {
            try {
                String firstLetter = fieldName.substring(0, 1).toUpperCase();String getter = "get" + firstLetter + fieldName.substring(1);
                Method method = o.getClass().getMethod(getter, new Class[] {});
                Object value = method.invoke(o, new Object[] {});
                return value;
            } catch (Exception e) {
               return null;
            }
     }

//list.sort(Comparator.comparing(OfficialProduct::getSort).reversed());  倒序
//list.sort(Comparator.comparing(OfficialProduct::getSort));  正序
    public static void main(String[] args) {
        String str="2020-01-01";
        System.out.println(getBirAgeSex("11111111").get("sexCode") == "M"?"男":"女");
        //System.out.println(getIsVideo("D://11//33333.jpg"));
    }
}
